package com.ielts.fragment;

import java.util.ArrayList;

import vn.com.baseapplication.BaseFragment;
import vn.com.baseapplication.constant.BaseConstant;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ielts.IeltsConstant;
import com.ielts.activity.IeltsApplication;
import com.ielts.activity.MainActivity;
import com.ielts.activity.R;
import com.ielts.activity.TopicActivity;
import com.ielts.fragment.adapter.TopicAdapter;
import com.ielts.model.ItemTopics;
import com.ielts.model.Tnx;
import com.ielts.services.IeltsUrl;

public class BuyedFragment extends BaseFragment implements OnItemClickListener,
		OnClickListener {

	MainActivity mActivity;
	private TopicAdapter listAllAdapter;
	private ArrayList<ItemTopics> listBuyedIelts = new ArrayList<>();
	private ListView listAll;
	private View loading;
	private View layoutHeader;
	private TextView tvHeader;

	String urlBuyedTopic;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mActivity = (MainActivity) getActivity();
		View layout = inflater.inflate(R.layout.fragment_buyed, null);
		listAll = (ListView) layout.findViewById(R.id.list);
		layoutHeader = (View) layout.findViewById(R.id.layout_header);
		tvHeader = (TextView) layout.findViewById(R.id.header_tv_year);
		loading = layout.findViewById(R.id.loading_all);

		listAllAdapter = new TopicAdapter(getActivity(), listBuyedIelts);
		listAll.setAdapter(listAllAdapter);
		listAll.setOnItemClickListener(this);

		layoutHeader.setOnClickListener(this);

		String userId = IeltsApplication.getInstance().getValue(
				IeltsConstant.KEY_USER_ID, IeltsConstant.KEY_USER_ID_DEF);
		urlBuyedTopic = IeltsUrl.URL_TOPIC_BUYED;
		urlBuyedTopic = urlBuyedTopic + "custId=" + userId;

		// getBoughtTopics();
		return layout;
	}

	@Override
	public void onResume() {
		super.onResume();
		try {
			getBoughtTopics();
		} catch (Exception e) {
		}
	}

	public void getBoughtTopics() {
		try {
			tvHeader.setText(IeltsApplication.getInstance().getValue(
					IeltsConstant.KEY_YEAR, IeltsConstant.KEY_YEAR_DEF));

			listBuyedIelts.clear();
			for (ItemTopics item : mActivity.listIelts) {
				if (item.topicType.equals("B")) {
					listBuyedIelts.add(item);
				}
			}
			listAllAdapter.notifyDataSetChanged();
			// network.get(IeltsConstant.GET_BOUGHT_TOPICS_FROM_SERVER,getActivity(),urlBuyedTopic);
		} catch (NullPointerException e) {
		}
	}

	@Override
	public void onNetSuccess(int requestId, String response) {
		if (response != null && response != "")
			network.setCache(urlBuyedTopic, response);
		onNetSuccessCache(requestId, response);
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		if (!intent.hasExtra(BaseConstant.MSG_FLAG)) {
			return;
		}

		String FLAG = intent.getStringExtra(BaseConstant.MSG_FLAG);
		if (FLAG != null && FLAG.equals(IeltsConstant.REFRESH_DATA + "")) {
			Log.e("REFRESH DATA", "BOUGTH FRAGMENT");
			getBoughtTopics();
		}
	}

	@Override
	public void onNetSuccessCache(int requestId, final String response) {
		super.onNetSuccessCache(requestId, response);

		super.onNetSuccess(requestId, response);
		try {
			switch (requestId) {
			case IeltsConstant.GET_BOUGHT_TOPICS_FROM_SERVER:
				Log.e("GET_BOUGHT_TOPICS_FROM_SERVER", response);

				mActivity.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						Gson gson = new Gson();
						Tnx tnx = gson.fromJson(response, Tnx.class);
						if (!tnx.Txns.isEmpty())
							network.setCache(urlBuyedTopic, response);
						listBuyedIelts.clear();

						for (int i = 0; i < mActivity.listIelts.size(); i++) {
							mActivity.listIelts.get(i).refreshData();
							for (Tnx.Transaction trans : tnx.Txns) {
								if (mActivity.listIelts.get(i).id.equals(trans.topicId)) {
									mActivity.listIelts.get(i).buyed = true;
									listBuyedIelts.add(mActivity.listIelts.get(i));

									break;
								}
							}
						}
						listAllAdapter.notifyDataSetChanged();
					}
				});

				break;

			default:
				break;
			}
		} catch (JsonSyntaxException e) {
			e.printStackTrace();
			Log.e("JSON ERR", response);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		ItemTopics itemTopic = listAllAdapter.getItem(position);
		itemTopic.buyed = true;
		Intent topicIntent = new Intent(getActivity(), TopicActivity.class);
		topicIntent.putExtra(BaseConstant.MSG_DATA, itemTopic);
		startActivity(topicIntent);
	}

	public void setLoading(final boolean isLoading) {
		mActivity.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				if (isLoading) {
					loading.setVisibility(View.VISIBLE);
				} else {
					loading.setVisibility(View.GONE);
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_header:
			((MainActivity) mActivity).setupSelectYearDialog().show();
			break;

		default:
			break;
		}
	}
}
